import React, { useState, useEffect, forwardRef, useImperativeHandle  } from "react"
import {
    Icon,
    Space,
    Popover,
    Input,
    Button
} from "@bytedance/mona-ui"
import './title.scss'
import { useAppDispatch } from "~store"
import {
    setAiTitle
} from "~store/controller/jinritemaiCopyGoods"

function getStrLen(str) {
    return str.replace(/[^\x00-\xff]/g, "aa").length
}

const TitleJiebaShers = (props, ref) => {
    const { searchWord, copyGoodConfig, titleLimitRule} = props
    if (!searchWord || searchWord.length === 0) return null
    if(!titleLimitRule) return null
    const {max_length, min_length} = titleLimitRule
    const dispatch = useAppDispatch()

    const { copynum } = copyGoodConfig
    function addTitleData() {
        let isAddList: number[] = []
        let addContent: string[] = []
        const getader = getTitleRefoter()
        return { title: getader.join(''), cuts: getader }
        function getTitleRefoter() {
            const miyer: number = Math.floor(Math.random() * searchWord.length)
            if (!isAddList.includes(miyer)) {
                const strs = searchWord[miyer].cell_info.query.query_value.value.value_str
                let interCount = strs.replace(/[^\x00-\xff]/g, "aa").length
                let interlength = addContent.join('').replace(/[^\x00-\xff]/g, "aa").length
                let outInterlength = max_length - interlength
                if (outInterlength >= interCount) {
                    addContent.push(searchWord[miyer].cell_info.query.query_value.value.value_str)
                    isAddList.push(miyer)
                    getTitleRefoter()
                }
            } else {
                getTitleRefoter()
            }
            return addContent
        }
    }

    function getTitleList() {
        let titleListCOntent: any[] = []
        for (let i = 0; i < copynum; i++) {
            const getader = addTitleData()
            titleListCOntent.push(getader)
        }
        return titleListCOntent
    }

    const [refoConterData, setRefoConterData] = useState<any[]>(getTitleList())
    // useEffect(() => {
    //     dispatch(setAiTitle(JSON.parse(JSON.stringify(refoConterData))))
    // }, [refoConterData])
    useImperativeHandle(ref, () => ({
        refoConterData
    }));
    useEffect(() => {
        if (refoConterData.length === copynum) {
            return
        }
        const addConter = copynum - refoConterData.length
        if (addConter > 0) {
            for (let i = 0; i < addConter; i++) {
                refoConterData.push(addTitleData())
            }
        } else {
            refoConterData.splice(addConter, Math.abs(addConter))
        }
        setRefoConterData([...refoConterData])
    }, [copynum])
    let movingDom
    const [addValue, setAddValue] = useState('')

    return (
        <div style={{
            marginLeft: 25
        }}>
            {refoConterData.map((item, index) => {
                return (<div className="lterconter" key={index}>
                    <Space direction="vertical">
                        <div className="titlebox">
                            标题{index + 1}(<span className="cine" style={{
                                color: (getStrLen(item.title) > max_length || getStrLen(item.title) < min_length) ? 'red' : '#565960'
                            }}>
                                {getStrLen(item.title)} / {max_length}
                            </span>)：{item.title}
                        </div>
                        <div className="boter teurdaonter" style={{
                            borderColor: (getStrLen(item.title) > max_length || getStrLen(item.title) < min_length) ? 'red' : '#f0f0f0'
                        }}>
                            {item.cuts.map((conter, conindex) => {
                                return (
                                    <div
                                        draggable
                                        className="tagconter"
                                        key={conindex}
                                        data-index={conindex}
                                        onDragStart={(e: any) => {
                                            setTimeout(_ => {
                                                e.target.classList.add('moving')
                                            })
                                            movingDom = e.target
                                            e.dataTransfer.effectAllowed = 'move'
                                        }}
                                        onDragEnd={(e: any) => {
                                            e.target.classList.remove('moving')
                                            item.title = ''
                                            movingDom.parentNode.childNodes.forEach((itemtit, index) => {
                                                item.title += itemtit.innerText
                                            })
                                            setRefoConterData([...refoConterData])
                                        }}
                                        onDragOver={(e) => {
                                            e.preventDefault()
                                        }}
                                        onDragEnter={(e: any) => {
                                            e.preventDefault()

                                            if (e.target === movingDom || e.target === movingDom.parentNode || e.target.parentNode !== movingDom.parentNode) {
                                                return
                                            }
                                            if (e.target.classList.contains('tagconter')) {
                                                const chlist = Array.from(movingDom.parentNode.childNodes)
                                                const movingIndex = chlist.indexOf(movingDom)
                                                const targetIndex = chlist.indexOf(e.target)
                                                if (movingIndex > targetIndex) {
                                                    movingDom.parentNode.insertBefore(movingDom, e.target)
                                                } else {
                                                    movingDom.parentNode.insertBefore(movingDom, e.target.nextElementSibling)
                                                }
                                            }
                                        }}>
                                        <span className="coneyr">
                                            <svg width="6" height="10" viewBox="0 0 6 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path fill-rule="evenodd" clip-rule="evenodd" d="M1 0C0.447715 0 0 0.447715 0 1C0 1.55228 0.447715 2 1 2C1.55228 2 2 1.55228 2 1C2 0.447715 1.55228 0 1 0ZM5 0C4.44772 0 4 0.447715 4 1C4 1.55228 4.44772 2 5 2C5.55229 2 6 1.55228 6 1C6 0.447715 5.55229 0 5 0ZM0 5C0 4.44772 0.447715 4 1 4C1.55228 4 2 4.44772 2 5C2 5.55229 1.55228 6 1 6C0.447715 6 0 5.55229 0 5ZM5 4C4.44772 4 4 4.44772 4 5C4 5.55229 4.44772 6 5 6C5.55229 6 6 5.55229 6 5C6 4.44772 5.55229 4 5 4ZM0 9C0 8.44772 0.447715 8 1 8C1.55228 8 2 8.44772 2 9C2 9.55229 1.55228 10 1 10C0.447715 10 0 9.55229 0 9ZM5 8C4.44772 8 4 8.44772 4 9C4 9.55229 4.44772 10 5 10C5.55229 10 6 9.55229 6 9C6 8.44772 5.55229 8 5 8Z" fill="#898B8F" />
                                            </svg>
                                        </span>
                                        <span className="timer itecnayer" >
                                            {conter}
                                        </span>
                                        <Icon
                                            type="CloseIcon"
                                            style={{
                                                cursor: 'pointer',
                                            }}
                                            onClick={(e: any) => {
                                                e.target.closest('.tagconter').remove()
                                                setTimeout(_ => {
                                                    const getTitle = document.querySelectorAll('.teurdaonter')
                                                    const nouer = getTitle[index].querySelectorAll('.itecnayer')
                                                    item.title = ''
                                                    nouer.forEach((itemtit: any, index) => {
                                                        item.title += itemtit.innerText
                                                    })
                                                    setRefoConterData([...refoConterData])
                                                })
                                            }}
                                        ></Icon>
                                    </div>
                                )
                            })}
                            <Popover
                                className="conetrss"
                                trigger="click"
                                content={
                                    <Space direction="vertical">
                                        <Input
                                            size="small"
                                            placeholder="请输入"
                                            style={{
                                                width: '150px',
                                            }}
                                            className="inouterdater"
                                            value={addValue}
                                            onChange={(e: any) => {
                                                setAddValue(e.target.value)
                                            }}

                                        ></Input>
                                        <Space >
                                            <Button type="primary"
                                                size="small"
                                                onClick={(e: any) => {
                                                    item.cuts.push(addValue)

                                                    setRefoConterData([...refoConterData])
                                                    setTimeout(_ => {
                                                        const getTitle: any = document.querySelectorAll('.teurdaonter')

                                                        const nouer = getTitle[index].querySelectorAll('.itecnayer')

                                                        item.title = ''
                                                        nouer.forEach((itemtit: any, index) => {

                                                            item.title += itemtit.innerText
                                                        })
                                                        setRefoConterData([...refoConterData])
                                                        getTitle[index].querySelector('.conetrss').click()
                                                    })
                                                    setAddValue('')
                                                }}>确定</Button>
                                            <Button
                                                size="small"
                                                onClick={(e) => {
                                                    setAddValue('')
                                                    const getTitle: any = document.querySelectorAll('.teurdaonter')
                                                    getTitle[index].querySelector('.conetrss').click()
                                                }}>取消</Button>
                                        </Space>
                                    </Space>
                                }
                            >
                                <div className="tagconter">
                                    <Icon
                                        type="AddIcon"
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                        onClick={(e: any) => {
                                            console.log('eee添加')
                                        }}
                                    ></Icon>
                                </div>
                            </Popover>

                        </div>
                        {getStrLen(item.title) > max_length && (
                            <div className="ciner" style={{
                                color: 'red',
                                fontSize: '12px',
                                // marginTop: '5px',
                            }}>最长不能超过{max_length}个字符</div>

                        )}
                        {getStrLen(item.title) < min_length && (
                            <div className="ciner" style={{
                                color: 'red',
                                fontSize: '12px',
                                // marginTop: '5px',
                            }}>最短不能少于{min_length}个字符</div>
                        )}
                    </Space>

                </div>)

            })}



        </div>
    )
}

export default forwardRef(TitleJiebaShers)